<template>
  <li class="todo" :class="{ editing: isEdit }">
    <div class="view">
      <input
        class="toggle"
        type="checkbox"
        :checked="isDone"
        @change="handleChange"
      />
      <label @dblclick="handleDbl">{{ text }}</label>
      <button class="destroy" @click="handleDel"></button>
    </div>
    <input
      ref="editInput"
      class="edit"
      type="text"
      v-model="value"
      @blur="isEdit = false"
      @keyup.enter="handleUpdate"
    />
  </li>
</template>

<script>
export default {
  props: {
    id: Number,
    text: String,
    isDone: Boolean,
  },
  inject: ["onUpdate", "onDelete"],
  data() {
    return {
      isEdit: false, // 表示当前是否为编辑状态
      value: "",
    };
  },
  methods: {
    handleDel() {
      const isOk = window.confirm("你确认要删除嘛");
      if (isOk) {
        // 触发自定义事件
        // this.$emit("delete", this.id);

        // 直接调用App组件提供下来的 onDelete 方法
        this.onDelete(this.id);
      }
    },

    handleChange(event) {
      // 获取操作元素的勾选状态
      const checked = event.target.checked;
      console.log("checked", checked);
      // 触发自定义事件
      // this.$emit("update", {
      //   id: this.id,
      //   isDone: checked,
      // });

      // 直接调用App组件提供下来的 onUpdate 方法
      this.onUpdate({
        id: this.id,
        isDone: checked,
      });
    },

    handleUpdate() {
      // this.$emit("update", {
      //   id: this.id,
      //   text: this.value,
      // });

      // 直接调用App组件提供下来的 onUpdate 方法
      this.onUpdate({
        id: this.id,
        text: this.value,
      });

      this.$refs.editInput.blur();
    },

    handleDbl() {
      this.isEdit = true; // 打开编辑框
      this.value = this.text;

      this.$nextTick(() => {
        this.$refs.editInput.focus();
      });
    },
  },
};
</script>
